package oop.ex3.nameserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.util.*;

public class MyNameServer {
	private int _localPort;
	private NameServerDataBase _myDataBase;
	private final int SERVER_SOCKET_TIMEOUT = 5 * 1000;
	private ServerSocket _listeningSocket;
	private List<SessionThread> _sessions;
	private volatile boolean _isListening;

	public static void main(String[] args) {
		MyNameServer newNameServer = new MyNameServer(args[0]);
		newNameServer.listenToRequests();
	
	}
	
	
	
	
	public MyNameServer(String port) {
		try {
			_localPort = Integer.parseInt(port);
			_listeningSocket = new ServerSocket(_localPort);
			//_listeningSocket.setSoTimeout(SERVER_SOCKET_TIMEOUT);
			_isListening = true;
			_myDataBase = new NameServerDataBase();
			_sessions = new ArrayList<SessionThread>();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}




	private void listenToRequests(){
		SessionThread newSessionThread;
		while(_isListening){
			try {
				newSessionThread = new SessionThread(_listeningSocket.accept(),_myDataBase);
				newSessionThread.start();
				_sessions.add(newSessionThread);
				if(newSessionThread.isGoAwayCommand()){
					_isListening = false;
				}
			} catch (SocketTimeoutException e) {
			} catch (IOException e) {
				//TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		closeNameServer();
	}




	private void closeNameServer() {
		for(SessionThread thread : _sessions){
				try {
					synchronized(thread){
					thread.join();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}



